package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vo.HotApArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper,ApArticle> implements IApArticleService {

    @Autowired
    private ApArticleMapper articleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerServiceImpl articleFreemarkerService;

    @Override
    public ResponseResult load(ArticleHomeDto dto, Long type) {
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            dto.setSize(10);
        }
        if (!type.equals(1) && !type.equals(2)) {
            type = 2L;
        }
        //文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag("__all__");
        }

        //时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());

        List<ApArticle> apArticles = articleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 保存和修改文章内容+文章配置+文章信息
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = null;
        //没有id，则是新增
        if (dto.getId() == null) {
            //1.保存文章信息
            apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            articleMapper.insert(apArticle);
            //2.保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            //3.保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //不是新增，是修改
            //1.先根据id去查询文章，然后修改
            apArticle = articleMapper.selectById(dto.getId());
            if (apArticle != null) {
                BeanUtils.copyProperties(dto,apArticle);
                articleMapper.updateById(apArticle);
                //2.先查询文章内容，在修改
                ApArticleContent apArticleContent =
                        apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                        .eq(ApArticleContent::getArticleId, apArticle.getId()));
                apArticleContent.setContent(dto.getContent());
                apArticleContentMapper.updateById(apArticleContent);
            }
        }
        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());

        ResponseResult responseResult=ResponseResult.okResult(apArticle==null?"":apArticle.getId());
        return responseResult;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 文章列表查询plus.查询的就是首页
     *
     * @param dto ,推荐频道  __all__  如果其他频道则是id
     * @param
     * @return
     */
    @Override
    public ResponseResult loadArticleList2(ArticleHomeDto dto) {
        String hotArticleVoListStr =null;
        //1.查询redis
        if(dto.getTag().equals("__all__")){
            hotArticleVoListStr= redisTemplate.opsForValue().get("hot_article_first_page" + dto.getTag());
        }else{//其他频道
            hotArticleVoListStr= redisTemplate.opsForValue().get("hot_article_first_page_" + dto.getTag());
        }

        //2.封装数据
        List<HotApArticleVo> articleVoList = JSONArray.parseArray(hotArticleVoListStr, HotApArticleVo.class);
        return ResponseResult.okResult(articleVoList);
    }
}
